package com.ruoyi.capsule.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.capsule.service.LoginWxService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service
public class LoginWxServiceImpl implements LoginWxService {
    @Autowired
    private ISysUserService userService;
    /**
     * 微信小程序登录
     *
     * @param code
     * @return
     */
    @Resource
    private AuthenticationManager authenticationManager;
    //引入redis
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TokenService tokenService;


    @Autowired
    private SysLoginService loginService;

    public AjaxResult wxlogin(String code) {
        //请求微信登录的地址
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", "wx1ce0d323ecff9862").replace("{1}", "981546ad863f53d6aceba691bb76b0b8").replace("{2}", code); //替换为需要的值
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));    //转为json格式接收
//请求成功后 获取数据
        String openid = jsonObject.getString("openid");
        String nickname = jsonObject.getString("nickname");
        String session_key = jsonObject.getString("session_key");
        redisTemplate.opsForValue().set("openid", openid);
        if (openid == null) {
            return AjaxResult.error("登录失败");
        }
        System.out.println("这里"+openid);
        System.out.println(openid);
        //查询用户是否存在，用来判断是否为第一次登录，记住openId是每个用户的标识
        SysUser sysUser = userService.selectUserByUserName(openid);

        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setUserName(openid);
            sysUser.setNickName("新用户");
            sysUser.setDeptId(3l);
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));

            userService.insertUser(sysUser);
        }
        //获取登录用户的信息
        sysUser = userService.selectUserByUserName(openid);
        LoginBody loginBody = new LoginBody();
        String token = loginService.login(openid, "123456", loginBody.getCode(),
                "546");
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest())

        AjaxResult ajax = AjaxResult.success();
            // 创建一个 HashMap 实例
            Map<String, String> tokenMap = new HashMap<>();
            // 将 token 存入 Map
            tokenMap.put("token", token);
            ajax.put("token", token);
            ajax.put("wxInfo",sysUser);
            ajax.put("userInfo",sysUser);

        return ajax;


    }

}
